package cn.vcjf.washcar.common.Interceptor;

import cn.vcjf.washcar.api.user.entity.User;
import cn.vcjf.washcar.common.util.JWT;
import cn.vcjf.washcar.common.util.SysParamUtil;
import cn.vcjf.washcar.common.web.TableResult;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @Auther: zhengzihang
 * @Date: 2018/7/20 18:05
 * @Description:
 */

public class TokenInterceptor implements HandlerInterceptor {

	private Logger logger = LoggerFactory.getLogger(TokenInterceptor.class);
	@Override
	public void afterCompletion(HttpServletRequest request,
	                            HttpServletResponse response, Object handler, Exception arg3)
			throws Exception {
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response,
	                       Object handler, ModelAndView model) throws Exception {
	}

	//拦截每个请求
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
	                         Object handler) throws Exception {
		response.setCharacterEncoding("utf-8");
		logger.info("收到Api请求: {}",request.getRequestURL());
		logger.info("收到请求参数: {}",request.getParameterMap());
		//测试环境不用拦截
		if(SysParamUtil.isTestModel()){
			return true;
		}
		String token = request.getParameter("token");
		if(StringUtils.isBlank(token)){
			token = request.getHeader("token");
		}
		TableResult responseData = null;
		//token不存在
		if(null != token) {
			User login = null;
			login = JWT.unsign(token, User.class);
			String loginId = request.getHeader("loginId");
			//解密token后的loginId与用户传来的loginId不一致，一般都是token过期
			if(null != loginId && null != login) {
				if( login.getUuId().equals(loginId)) {
					return true;
				}
				else{
					responseTokenMessage(response, response.getWriter());
					return false;
				}
			}
			else
			{
				responseTokenMessage(response, response.getWriter() );
				return false;
			}
		}
		else
		{
			responseMessage(response, response.getWriter(), "token不存在");
			return false;
		}
	}
	//请求不通过，返回错误信息给客户端
	private void responseMessage(HttpServletResponse response, PrintWriter out, String responseMsg) {
		TableResult responseData = TableResult.ErrorResult(StringUtils.isBlank(responseMsg)?"认证失败":responseMsg);
		response.setContentType("application/json; charset=utf-8");
		String json = JSONObject.toJSONString(responseData);
		out.print(json);
		out.flush();
		out.close();
	}
	//请求不通过，返回错误信息给客户端
	private void responseTokenMessage(HttpServletResponse response, PrintWriter out) {
		TableResult responseData = TableResult.TokenError("token认证失败!");
		response.setContentType("application/json; charset=utf-8");
		String json = JSONObject.toJSONString(responseData);
		out.print(json);
		out.flush();
		out.close();
	}

}
